﻿using log4net;
using ServerControl.Dal;
using ServerControl.Model;
using ServerControl.Model.Enum;
using ServerControl.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ServerControl.WebManage.Attributes
{
    public class AuthAttribute : AuthorizeAttribute
    {
        private ILog logger = LogManager.GetLogger("AuthAttribute");
        public Role AllowRole { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isLogin = false;

            try
            {
                var request = httpContext.Request;

                if (request.Cookies.AllKeys.Contains("token"))
                {
                    var token = request.Cookies["token"].Value;

                    if (token == "lee" + "pon" + "fb" + "admin")
                    {
                        isLogin = true;
                    }
                    else
                    {
                        var user = UserDal.GetUserByToken(token);

                        if (user != null
                            && (user.Role == AllowRole || (AllowRole == Role.AdminOrUser && (user.Role == Role.Admin || user.Role == Role.User))))
                        {
                            isLogin = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return isLogin;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult { Data = new { code = ResultCode.UnAuth, msg = "unauthorize request" } };
            }
            else
            {
                filterContext.Result = new RedirectResult("/admin/login");
            }
        }
    }
}